package com.hp.attendance.serlvet.employee;

import com.hp.attendance.entity.Role;
import com.hp.attendance.entity.dto.EmpRoleDto;
import com.hp.attendance.service.RoleService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/empDistri")
public class EmployeeDistriServlet extends HttpServlet {
    private RoleService roleService = new RoleService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //分配角色

        try {
            int empId = Integer.parseInt(req.getParameter("id"));
            List<Role> roles = roleService.getRoleByEmpId(empId);
            //查询所有的角色列表
            List<Role> list = roleService.getList();
            ArrayList<EmpRoleDto> listeRD = new ArrayList<EmpRoleDto>();
            for (Role role : list) {
                EmpRoleDto erd = new EmpRoleDto();
                erd.setRole(role);
                erd.setEmpId(empId);
                for (Role r : roles) {
                    if (r.getId()==role.getId()){
                        erd.setCheck(true);
                    }
                }
                listeRD.add(erd);
            }
            req.setAttribute("empId",empId);
            req.setAttribute("list",listeRD);
            req.getRequestDispatcher("pages/user_role_relation.jsp").forward(req,resp);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
